<template>
	<uni-popup ref="popup" type="center" style="z-index: 910" :is-mask-click="false">
		<view class="package" style="width:680rpx;padding:30rpx;">
			<view class="title">验证以下信息可膨胀{{gemBei}}倍蓝宝石 </view>
			<view class="top">请输入手机号</view>
			<input class="uni-input" maxlength="11" type="number" @input="onInput($event, 'phone')" :value="phone" />
			<!-- 	<view class="top">请输入验证码</view>
			<view class="space-between" style="width:100%;">
				<input class="uni-input" type="number" maxlength="4" @input="onInput($event, 'code')" :value="code"
					style="width: 70%;" />
				<view v-show="canSendcode" class="_code" @click="toSendCode()">获取验证码</view>
				<view v-show="!canSendcode" class="_code">{{ countdown }}s</view>
			</view> -->
			<view class="top">请上传车牌号照片<text style="color:#468FF5;margin-left:10rpx">(一个车牌号可绑定两个账号)</text></view>
			<mk-upload :imgList="imgList" @onDelete="onDelete" @onChoose="onChoose" :maxCount="1" />
			<view class="top">请确认系统识别车牌号是否正确,<text style="color:#468FF5;margin-left:10rpx"
					@click="onDelete()">重新上传</text>
			</view>
			<!-- @click="openPlatePicker()" -->
			<view class="centers">
				<view v-for="(item,index) in 7" :key="index" :style="{display:numberplate?'none':'block'}"></view>
				<view v-for="(item,index) in list" :key="index" :style="{display:!numberplate?'none':'block'}">{{item}}
				</view>
			</view>
			<view class="space-between but">
				<view @click="submit(1)">取消</view>
				<view @click="submit(2)">确定</view>
			</view>
			<view class="top" style="color:#468FF5;width:100%;text-align: center;" @click="telCall('400-109-1606')">
				联系客服>>
			</view>
		</view>
	</uni-popup>
	<!-- 车牌弹框 -->
	<VehiclePlatePad v-if="isShowPlatePad" @cancel="isShowPlatePad = false" @confirm="confirmPlate" />
	<!-- 达到上限提示 -->
	<uni-popup ref="upper" type="center" style="z-index: 910" :is-mask-click="false">
		<view class="package" style="width:650rpx;padding:30rpx;">
			<view>{{text}}</view>
			<view class="space-between but">
				<view @click="upperClose()">取消</view>
				<view @click="telCall('400-109-1606')">联系客服</view>
			</view>
		</view>
	</uni-popup>
	<Watermark ref="watermark" @selected="selected"></Watermark>
</template>

<script setup lang="ts">
	import VehiclePlatePad from '@c/earthPushing/common/VehiclePlatePads.vue';
	import Watermark from '@c/watermark.vue';
	import { ref, nextTick, onBeforeUnmount } from 'vue';
	import { errorToast, showLoading, showToast, successToast } from '@/utils/prompt';
	import { toPublish } from '@mqtt';
	import { getDriverID } from '@/stores/driverID';
	import { useUserStore } from '@/stores/user';
	import { telCall } from '@/utils/copyText';
	defineProps({
		gemBei: {
			type: Number,
			default: 7,
		}
	});
	const driver_id = getDriverID();
	const userInfo = useUserStore();
	let intervalID = 0;
	const popup = ref(null)
	const phone = ref('');
	const code = ref('');
	const countdown = ref(60);
	const isSendingCode = ref(false);
	const canSendcode = ref(true);
	const emit = defineEmits(['confirm']);

	// 上传图片
	const imgList = ref([])
	const image = ref()
	const watermark = ref(null)

	const isShowPlatePad = ref(false); //添加车牌弹框
	const numberplate = ref(''); //车牌号

	const car = ref('')
	const list = ref([])

	const upper = ref(null)
	const text = ref()

	// 上传图片
	function onChoose(e : any) {
		watermark.value.fillTextToImg(e.tempFilePaths[0])
		console.log(e.tempFilePaths[0])
	}
	function selected(e : any) {
		uni.uploadFile({
			url: 'https://admin.anlan.tech/api/common/upload2',
			filePath: e,
			name: 'file',
			formData: {
				'user': 'test'  // 上传附带参数
			},
			success: (uploadFileRes) => {
				console.log(JSON.stringify(uploadFileRes.data))
				const state = JSON.parse(uploadFileRes.data).data
				// numberplate.value = state.cart_code ? state.cart_code : '';
				// list.value = numberplate.value ? numberplate.value.split('') : []
				// 根据接口具体返回格式   赋值具体对应url
				imgList.value.push(state.fullurl)
				image.value = state.url
				analyzing(state.fullurl)
			},
			fail: (err : any) => {
				console.log('err', err)
			}
		});
	}
	//获取车牌号
	function analyzing(img : string) {
		uni.request({
			url: 'https://orm.anlan.tech/ocr.php?cmd=getCartCode', //仅为示例，并非真实接口地址。
			data: {
				image: img
			},
			success: (res) => {
				car.value = res.data && res.data.data ? res.data.data : '';
				numberplate.value = res.data.data ? res.data.data : '';
				list.value = numberplate.value ? numberplate.value.split('') : []
			}
		});
	}
	// 删除图片
	function onDelete() {
		imgList.value = []
		image.value = ''
	}
	/**
	  * 打开/关闭车牌弹框
	  */
	function openPlatePicker() {
		isShowPlatePad.value = true
	}

	//新增车牌
	function confirmPlate(plate : string) {
		numberplate.value = plate;
		isShowPlatePad.value = false;
		list.value = plate.split('')
		// list.value.splice(2, 0, "")
		console.log(list.value)
	}

	function onInput(evt : any, type : string) {
		const { detail } = evt;
		const rule = /[^\d]/g;
		const value = detail.value.replace(rule, '');
		nextTick(() => {
			switch (type) {
				case 'phone':
					phone.value = value;
					break;
				case 'code':
					code.value = value;
					break;
			}
		});
	}

	function validatePhone() {
		const rule = /^1[3-9]\d{9}$/;
		return rule.test(phone.value);
	}

	function toSendCode() {
		if (!isSendingCode.value) {
			if (validatePhone()) {
				sendCode();
			} else {
				showToast('请输入有效的手机号码');
			}
		}
	}
	function startCountdown() {
		canSendcode.value = false;
		countdown.value = 60;
		// @ts-ignore
		intervalID = setInterval(() => {
			countdown.value -= 1;
			if (countdown.value === 0) {
				clearInterval(intervalID);
				canSendcode.value = true;
			}
		}, 1000);
	}
	function sendCode() {
		showLoading();
		isSendingCode.value = true;
		const payload = {
			event: 'notice',
			mobile: phone.value,
		};
		toPublish('driver/sendSms', payload, (obj : any) => {
			isSendingCode.value = false;
			startCountdown();
			successToast('发送成功');
		});
	}
	function submit(num : number) {
		close()
		switch (num) {
			case 1:
				const payload = {
					driver_id
				};
				toPublish('score/cencelSms', payload, (obj : any) => {
					const { code, msg } = obj;
					if (code === 1) {
						// emit('confirm');
					} else {
						errorToast(msg)
					}
				});
				break;
			case 2:
				if (!phone.value) {
					showToast('请输入手机号码');
					return
				} else if (!validatePhone()) {
					showToast('请输入正确手机号码');
					return
				} else if (!image.value) {
					showToast('请上传车牌号照片');
					return
				} else if (!numberplate.value) {
					showToast('请上传车牌号照片');
					return
				}else {
					updatePhone()
				}
				break;
		}
	}
	function updatePhone() {
		showLoading('正在提交');
		const payload1 = {
			mobile: phone.value,
			captcha: code.value,
			driver_id,
			cart_code: numberplate.value,
			cart_image: image.value,
		};
		toPublish('score/checkSms', payload1, (obj : any) => {
			const { code, msg } = obj;
			text.value = msg
			if (code === 1) {
				userInfo.gemstone()
				emit('confirm');
			} else {
				upperOpen()
			}
		});
	}
	function open() {
		popup.value.open();
	}
	function close() {
		popup.value.close();
	}
	function upperOpen() {
		upper.value.open()
	}
	function upperClose() {
		upper.value.close()
	}
	onBeforeUnmount(() => {
		clearInterval(intervalID);
	});
	defineExpose({
		open,
		close,
	});
</script>

<style scoped lang="less">
	.title {
		font-size: 36rpx;
		font-family: Alibaba PuHuiTi;
		font-weight: 400;
		// color: #468FF5;
		margin-bottom: 10rpx;
		width: 100%;
		text-align: center;
	}

	.top {
		font-size: 26rpx;
		font-family: Alibaba PuHuiTi;
		font-weight: 400;
		color: #333333;
		margin: 20rpx 0px;
	}

	input {
		height: 69rpx;
		background: #F5F9FF;
		border: 1px solid #D3D3D3;
		border-radius: 5px;
		padding: 0rpx 15rpx;
		box-sizing: border-box;
	}

	._code {
		width: 27%;
		height: 69rpx;
		background: #468FF5;
		border-radius: 5px;
		font-size: 26rpx;
		font-weight: 400;
		color: #FFFFFF;
		text-align: center;
		line-height: 69rpx;
	}

	.but {
		width: 100%;
		justify-content: space-around;
		margin: 60rpx 0px 20rpx;

		view {
			width: 230rpx;
			height: 69rpx;
			border-radius: 5px;
			text-align: center;
			line-height: 69rpx;
		}

		view:nth-of-type(1) {
			color: #468FF5;
			border: 1px solid #468FF5;
			box-sizing: border-box;
		}

		view:nth-of-type(2) {
			background: #468FF5;
			color: #FFF;
		}
	}

	.centers {
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;

		// view:nth-of-type(3) {
		// 	width: 9rpx;
		// 	height: 9rpx;
		// 	border-radius: 50%;
		// 	background-color: #666;
		// 	border: 0px;
		// }

		// view:nth-of-type(10) {
		// 	width: 9rpx;
		// 	height: 9rpx;
		// 	border-radius: 50%;
		// 	background-color: #666;
		// 	border: 0px;
		// }

		view {
			width: 72rpx;
			height: 72rpx;
			background: #F5F9FF;
			border: 1px solid #D3D3D3;
			border-radius: 5px;
			text-align: center;
			line-height: 78rpx;
		}
	}
</style>
<style>
	.package>>>.mk-upload {
		padding: 0px;
	}

	.package>>>.mk-upload_item {
		margin: 0px;
	}
</style>